﻿using Autofac;
using Autofac.Core;
using Autofac.Extensions.DependencyInjection;
using FlyingEye.HttpServices;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
using System.IO;

namespace FlyingEye
{
    public class FlyingEyeAdminModule
    {
        private void ConfigureLogger()
        {
            Log.Logger = new LoggerConfiguration()
#if DEBUG
            .MinimumLevel.Debug()
#else
            .MinimumLevel.Information()
#endif
            // 将 Microsoft 命名空间下的日志级别设置为 Information，这意味着来自 Microsoft 命名空间的日志将按 Information 级别进行记录。
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            // 将 Microsoft.EntityFrameworkCore 命名空间下的日志级别设置为 Warning，
            // 这意味着来自 Microsoft.EntityFrameworkCore 命名空间的日志将按 Warning 级别进行记录。
            .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
            // 将当前的日志上下文（LogContext）包含在每个日志事件中。
            .Enrich.FromLogContext()
            // 将日志记录到一个名为 "logs.txt" 的文件中。Async 方法表示日志写入是异步执行的，以提高性能。
            .WriteTo.Async(c => c.File("Logs/logs.txt"))
            // 将日志输出到控制台。
            .WriteTo.Async(c => c.Console())
            .CreateLogger();
        }

        public void ConfigureHost(IHostBuilder builder)
        {
#if RELEASE
            builder.UseEnvironment(Environments.Production);
#else
            builder.UseEnvironment(Environments.Development);
#endif
            // 替换使用 autofac 容器
            builder.UseServiceProviderFactory(new AutofacServiceProviderFactory())
                .ConfigureContainer<ContainerBuilder>(builder =>
                {
                    builder.RegisterModule<AutofacModule>();
                });

            ConfigureLogger();
            builder.UseSerilog();
        }

        public void ConfigureServices(HostBuilderContext context, IServiceCollection services)
        {
            //builder.Logging.ClearProviders();
            //builder.Logging.AddSerilog();

            services.AddLogging(config => config.AddSerilog());

            // 添加配置选项
            services.Configure<HttpClientServiceOptions>(context.Configuration.GetSection(key: nameof(HttpClientServiceOptions)));
            services.Configure<HttpUrlsOptions>(context.Configuration.GetSection(key: nameof(HttpUrlsOptions)));

            // 添加 HttpClient
            services.AddHttpClient();

            services.AddAutoMapper(configuration =>
            {
                // 添加 automapper 映射
            });

        }
    }
}
